<?php
/*
Plugin Name: cnblogs
Plugin URI: http://www.hengha.info
Description: Crawl blog from http://www.cnblogs.com/
Version: 1.0
Author: tomcat
Author URI: http://www.hengha.info
Text Domain: cnblogs
Domain Path: /languages/
*/

/*
function cnblogs_add_small_interval($schedules)
{
    if (!isset($schedules['ten-minutes'])) {
        $schedules['ten-minutes'] = array(
            'interval' => 600,
            'display' => __('Ten Minutes', 'cnblogs')
        );
    }
    if (!isset($schedules['three-minutes'])) {
        $schedules['three-minutes'] = array(
            'interval' => 180,
            'display' => __('Three Minutes', 'cnblogs')
        );
    }

    return $schedules;
}
*/

//add_filter('cron_schedules', 'cnblogs_add_small_interval');

/*
function load_plugin_textdomain() {
  load_plugin_textdomain( 'qiushibaike', FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
}

add_action( 'plugins_loaded', 'load_plugin_textdomain' );
 */

function cnblogs_prefix_activation()
{
    //wp_schedule_event(time(), 'ten-minutes', 'cnblogs_ten_minutes_event_hook');
    //wp_schedule_event(time(), 'three-minutes', 'cnblogs_three_minutes_event_hook');
    wp_schedule_event(time(), 'hourly', 'cnblogs_hourly_event_hook');
}

register_activation_hook(__FILE__, 'cnblogs_prefix_activation');

function cnblogs_get_anonymous_user_id()
{
    $userId = username_exists('unkown');
    if ($userId == null) {
        $userId = wp_insert_user(array(
            'user_login' => 'cnblogs',
            'user_email' => 'cnblogs@hengha.info',
            'nickname' => '博客园',
            'display_name' => '博客园',
            'user_pass' => wp_generate_password(20),
            'role' => 'subscriber'
        ));
    }
    return $userId;
}

function cnblogs_get_user_id($user)
{
    if ($user) {
        $userId = username_exists($user);
        if ($userId == null) {
            $userId = wp_insert_user(array(
                'nickname' => $user,
                'display_name' => $user,
                'user_login' => $user,
                'user_email' => $user . '@cnblogs.com',
                'user_pass' => wp_generate_password(20),
                'role' => 'subscriber'
            ));
        }
        return $userId;
    } else {
        return get_anonymous_user_id();
    }
}

function cnblogs_handle_blog_list($xml)
{
    $args = array(
        'post_type' => 'post',
        'post_status' => 'any',
        'meta_key' => 'item-id',
        'posts_per_page' => 1
    );

    $categoryId = get_cat_ID('博客园');
    foreach ($xml->children() as $blog) {
        if ($blog->getName() == 'entry') {
            $model = new stdClass();

            foreach ($blog as $child) {
                $model->{$child->getName()} = strval($child);
            }
            $t = str_replace('http://www.cnblogs.com/', '', $model->id);
            $user_name = substr($t, 0, strpos($t, '/'));
            $userId = cnblogs_get_user_id($user_name);
            $item_id = str_replace('.html', '', substr($model->id, strrpos($model->id, '/') + 1));
            $args['meta_value'] = $item_id;
            $the_post = get_posts($args);
            if (!$the_post) {
                $tags = array('博客园');
                $postId = wp_insert_post(array(
                    'post_title' => $model->title,
                    'post_content' => $model->content,
                    'post_excerpt' => $model->summary,
                    'post_name' => 'cnblogs-' . $item_id,
                    'post_status' => 'publish',
                    'post_author' => $userId,
                    'post_type' => 'post',
                    'post_category' => array($categoryId),
                    'tags_input' => implode(',', $tags)
                ));

                update_post_meta($postId, 'published_at', $model->published);
                update_post_meta($postId, 'url', $model->id);
                update_post_meta($postId, 'item-id', $item_id);
            }
        }
    }
}

function cnblogs_get_blog_list()
{
    /*
    $args = array(
        'user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
        'httpversion' => '1.1',
        'timeout' => 120
    );
    $content = wp_remote_get('http://feed.cnblogs.com/blog/picked/rss', $args);
    if (is_wp_error($content)) {
        error_log(sprintf("request cnblogs failed"));
        return;
    }
    $xml = simplexml_load_string($content['body']);
    */
    $xml = simplexml_load_string(file_get_contents('http://feed.cnblogs.com/blog/picked/rss'));
    cnblogs_handle_blog_list($xml);
}

/*
function cnblogs_get_blog_content()
{

}
*/

function cnblogs_shortcode_get_list($attrs){
    cnblogs_get_blog_list();
}
add_shortcode('cnblogs','cnblogs_shortcode_get_list');
add_filter("mce_external_plugins", "cnblogs_register_tinymce_plugin");
add_filter('mce_buttons', 'cnblogs_add_tinymce_button');
function cnblogs_register_tinymce_plugin(){
    $plugin_array['cnblogs_button'] = plugins_url().'/cnblogs/js/oschina-shortcode.js';
    return $plugin_array;
}
function cnblogs_add_tinymce_button(){
    $buttons[] = "cnblogs_button";
    return $buttons;
}


add_action('cnblogs_hourly_event_hook', 'cnblogs_get_blog_list');
//add_action('cnblogs_ten_minutes_event_hook', 'cnblogs_get_blog_content');
function cnblogs_prefix_deactivation()
{
    //wp_clear_scheduled_hook('cnblogs_ten_minutes_event_hook');
    //wp_clear_scheduled_hook('cnblogs_three_minutes_event_hook');
    wp_clear_scheduled_hook('cnblogs_hourly_event_hook');
}

register_deactivation_hook(__FILE__, 'cnblogs_prefix_deactivation');
?>
